/**
 * @JedisRpcNamingService.java  COPYRIGHT xiaojian
 * 
 * Created on 2017年1月5日 下午6:26:06
 */
package xt.toolkit.rpc.naming.jedis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Preconditions;

import xiaojian.toolkit.redis.Jedis2Commands;
import xt.toolkit.rpc.naming.RpcNamingService;
import xt.toolkit.rpc.naming.RpcNode;

/**
 * jedis实现一个命名服务。
 * 
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class JedisRpcNamingService implements RpcNamingService {

	@Autowired
	private Jedis2Commands jedis = null;

	public Jedis2Commands getJedis() {
		return jedis;
	}

	public void setJedis(Jedis2Commands jedis) {
		this.jedis = jedis;
	}

	/**
	 * @see xt.toolkit.rpc.naming.RpcNamingService#randomGetNode(java.lang.String)
	 */
	@Override
	public RpcNode randomGetNode(String serviceName) {
		Preconditions.checkArgument(StringUtils.isNoneBlank(serviceName));

		String key = String.format(RpcRedisKeyConstants.RPC_SERVICE_NODE_LST, serviceName);
		int size = jedis.scard(key).intValue();
		if (size == 0) {
			return null;
		}

		String nodeName = jedis.srandmember(key);
		String nodeKey = String.format(RpcRedisKeyConstants.RPC_NODE, nodeName);

		String ipAddress = jedis.hget(nodeKey, RpcRedisKeyConstants.RPC_NODE_ATTR_ADDR);
		String strPort = jedis.hget(nodeKey, RpcRedisKeyConstants.RPC_NODE_ATTR_PORT);

		RpcNode rpcNode = new RpcNode();
		rpcNode.setIpAddress(ipAddress);
		rpcNode.setName(nodeName);
		rpcNode.setPort(Integer.parseInt(strPort));
		return rpcNode;
	}

}
